#include "domainwhoisdlg.h"
//#include <QVBoxLayout>
//#include <QLabel>
#include "tdomain.h"

DomainWhoisDlg::DomainWhoisDlg(QWidget *parent)
    : QDialog(parent)
{
    // 初始化UI组件
    QVBoxLayout *layout = new QVBoxLayout(this);
    layout->addWidget(new QLabel(tr("域名后缀:")));
    m_nameLineEdit = new QLineEdit;
    layout->addWidget(m_nameLineEdit);

    layout->addWidget(new QLabel(tr("WhoIs服务地址:")));
    m_ageLineEdit = new QLineEdit;
    layout->addWidget(m_ageLineEdit);

    layout->addWidget(new QLabel(tr("端口:")));
    m_idComboBox = new QComboBox;
    layout->addWidget(m_idComboBox);

    //m_createButton = new QPushButton(tr("Create Table"));
    m_insertButton = new QPushButton(tr("增加"));
    m_updateButton = new QPushButton(tr("更新"));
    m_deleteButton = new QPushButton(tr("删除"));
    m_displayButton = new QPushButton(tr("查询"));
//
    //layout->addWidget(m_createButton);
    layout->addWidget(m_insertButton);
    layout->addWidget(m_updateButton);
    layout->addWidget(m_deleteButton);
    layout->addWidget(m_displayButton);

    m_tableView = new QTableView;
    layout->addWidget(m_tableView);

    // 连接按钮信号与槽函数
    //connect(m_createButton, &QPushButton::clicked, this, &DomainWhoisDlg::createTable);
    connect(m_insertButton, &QPushButton::clicked, this, &DomainWhoisDlg::insertRecord);
    connect(m_updateButton, &QPushButton::clicked, this, &DomainWhoisDlg::updateRecord);
    connect(m_deleteButton, &QPushButton::clicked, this, &DomainWhoisDlg::deleteRecord);
    connect(m_displayButton, &QPushButton::clicked, this, &DomainWhoisDlg::displayRecords);

    m_tDomain = static_cast<TDomain *>(QWidget::parentWidget());
    m_db = m_tDomain->m_dbMySql->m_mysqlConn;
//    m_db = QSqlDatabase::addDatabase("QMYSQL");
//    m_db.setHostName("10.35.19.63"); // 替换为你的MySQL服务器地址
//    m_db.setDatabaseName("tdomainmgr"); // 替换为你的数据库名
//    m_db.setUserName("tDomainMgr"); // 替换为你的用户名
//    m_db.setPassword("HaniLcjyaYPeWkes"); // 替换为你的密码

    openDatabase();
}
DomainWhoisDlg::~DomainWhoisDlg()
{
    m_db.close();
}

void DomainWhoisDlg::openDatabase()
{
//    if (!m_db.open()) {
//        QMessageBox::critical(this, tr("Error"), tr("Could not open database.") + m_db.lastError().text(), QMessageBox::Cancel);
//        return;
//    }
    //createTable();
    fillComboBoxWithIds();
    displayRecords();
}

void DomainWhoisDlg::createTable()
{
    QSqlQuery query(m_db);
    QString createTableStatement = "CREATE TABLE IF NOT EXISTS MyTable (ID INT AUTO_INCREMENT PRIMARY KEY, Name VARCHAR(255), Age INT)";
    if (!execQuery(createTableStatement)) {
        QMessageBox::critical(this, tr("Error"), tr("Could not create table."));
    }
}

void DomainWhoisDlg::insertRecord()
{
    QString name = m_nameLineEdit->text();
    QString ageStr = m_ageLineEdit->text();
    bool ok;
    int age = ageStr.toInt(&ok);
    if (!ok || name.isEmpty() || age <= 0) {
        QMessageBox::warning(this, tr("Warning"), tr("Invalid input! Please enter a valid name and age."));
        return;
    }

    QString insertStatement = "INSERT INTO whois_query_addr (domainsuffix, queryaddr,port) VALUES (?, ?)";
    if (execQuery(insertStatement, {name, QString::number(age)})) {
        QMessageBox::information(this, tr("Success"), tr("Record inserted successfully."));
        clearInputFields();
        displayRecords();
    }
}

void DomainWhoisDlg::updateRecord()
{
    int id = m_idComboBox->currentData().toInt();
    if (id <= 0) {
        QMessageBox::warning(this, tr("Warning"), tr("Please select a record to update."));
        return;
    }

    QString name = m_nameLineEdit->text();
    QString ageStr = m_ageLineEdit->text();
    bool ok;
    int age = ageStr.toInt(&ok);
    if (!ok || name.isEmpty() || age <= 0) {
        QMessageBox::warning(this, tr("Warning"), tr("Invalid input! Please enter a valid name and age."));
        return;
    }

    QString updateStatement = "UPDATE whois_query_addr SET domainsuffix = ?, queryaddr = ? ,port =? WHERE ID = ?";
    if (execQuery(updateStatement, {name, QString::number(age), QString::number(id)})) {
        QMessageBox::information(this, tr("Success"), tr("Record updated successfully."));
        displayRecords();
    }
}

void DomainWhoisDlg::deleteRecord()
{
    int id = m_idComboBox->currentData().toInt();
    if (id <= 0) {
        QMessageBox::warning(this, tr("Warning"), tr("Please select a record to delete."));
        return;
    }

    QString deleteStatement = "DELETE FROM whois_query_addr WHERE ID = ?";
    if (execQuery(deleteStatement, {QString::number(id)})) {
        QMessageBox::information(this, tr("Success"), tr("Record deleted successfully."));
        clearInputFields();
        displayRecords();
    }
}

void DomainWhoisDlg::displayRecords()
{
    m_model = new QSqlTableModel(this, m_db);
    m_model->setTable("whois_query_addr");
    m_model->select();

    m_tableView->setModel(m_model);
    m_tableView->resizeColumnsToContents();
}

bool DomainWhoisDlg::execQuery(const QString &sql, const QStringList &params)
{
    QSqlQuery query(m_db);
    query.prepare(sql);
    for (int i = 0; i < params.size(); ++i) {
        query.bindValue(i + 1, params[i]);
    }

    if (!query.exec()) {
        QMessageBox::critical(this, tr("Error"), tr("Could not execute SQL statement:") + query.lastError().text());
        return false;
    }
    return true;
}

void DomainWhoisDlg::fillComboBoxWithIds()
{
    m_idComboBox->clear();
    QSqlQuery query(m_db);
    query.exec("SELECT ID FROM whois_query_addr");
    while (query.next()) {
        m_idComboBox->addItem(query.value(0).toString(), query.value(0));
    }
}

void DomainWhoisDlg::clearInputFields()
{
    m_nameLineEdit->clear();
    m_ageLineEdit->clear();
    m_idComboBox->setCurrentIndex(-1);
}
